import { createSSRApp } from 'vue'
import App from './App.vue'
import pinia from '@/store/index'
// import uviewPlus from 'uview-plus';
import i18n from './i18n.js'
import { isDevelopment } from './utils/utils'
import { useUserInfo } from '@/store/user'

// let deferredPrompt: any;

// window.addEventListener('beforeinstallprompt', (e) => {
//   e.preventDefault();
//   deferredPrompt = e;

//   const installButton = document.getElementById('installButton');
//   if (installButton) {
//     installButton.style.display = 'block';

//     installButton.addEventListener('click', () => {
//       installButton.style.display = 'none';
//       deferredPrompt.prompt();
//       deferredPrompt.userChoice.then((choiceResult: any) => {
//         if (choiceResult.outcome === 'accepted') {
//           console.log('User accepted the A2HS prompt');
//         } else {
//           console.log('User dismissed the A2HS prompt');
//         }
//         deferredPrompt = null;
//       });
//     });
//   }
// });
// 定义具名处理函数
const handleBeforeInstallPrompt = (e) => {
  e.preventDefault()
  console.log('🔥 beforeinstallprompt fired')
  useUserInfo().setDeferredPrompt(e)
}
// 解绑时调用
window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
// 添加监听器
window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    const urlPree = isDevelopment()
    navigator.serviceWorker
      .register(urlPree + '/static/pwa/sw.js')
      .then((registration) => {
        registration.update()
        console.log('SW registered:', registration)
      })
      .catch((error) => {
        console.log('SW registration failed:', error)
      })
  })
}

export function createApp() {
  const app = createSSRApp(App)

  // 获取系统信息
  uni.getSystemInfo({
    success: function (e) {
      // #ifndef MP
      app.config.globalProperties.$StatusBar = e.statusBarHeight
      if (e.platform === 'android') {
        app.config.globalProperties.$CustomBar = e.statusBarHeight + 50
      } else {
        app.config.globalProperties.$CustomBar = e.statusBarHeight + 45
      }
      // #endif

      // #ifdef MP-WEIXIN
      app.config.globalProperties.$StatusBar = e.statusBarHeight
      const custom = wx.getMenuButtonBoundingClientRect()
      app.config.globalProperties.$Custom = custom
      app.config.globalProperties.$CustomBar = custom.bottom + custom.top - e.statusBarHeight
      // #endif

      // 窗口高度
      app.config.globalProperties.$windowHeight = e.windowHeight
      // 获取导航高度
      app.config.globalProperties.$navHeight = e.statusBarHeight * (750 / e.windowWidth) + 91
      app.config.globalProperties.$SystemInfo = e
    },
  })

  app.use(pinia)

  // 确保 uviewPlus 插件已经初始化后，再调用 setConfig
  // 调用 setConfig 方法之前，确保 uviewPlus 插件已经初始化

  app.use(i18n)
  //   app.use(uviewPlus)
  return {
    app,
  }
}
